<template>
    <view class="add-blog">
        <view class="content">
            <u-input v-model="form.content" type="textarea" />
        </view>
		<view class="images">
			<u-upload ref="uUpload" @update:file-list="onListChange" :action="action" :file-list="fileList" @on-change="onChange" ></u-upload>
		</view>
		<u-button @click="submit">提交</u-button>
    </view>
</template>
    
<script setup lang='ts'>

import { apiCreateBlog } from '@/api/blog';
import { baseUrl } from '@/api/request';
import { uToast } from '@/component/uTools';
import { userStore } from '@/store/user';
import { storeToRefs } from 'pinia';
import { ref, toRaw } from 'vue';

	const store = userStore();
	const { userInfo } = storeToRefs(store); // 把store转成响应式
	const action = baseUrl + 'upload';
	const fileList = ref([]);
	const lists = ref([]);
	const form = ref({
		type: 1,
		title: '',
		content: '',
		images: '',
		userid: userInfo.value.id
	})
	// const uUpload = ref();
	const onChange = (res: any, index: number, lists: any, name: string) => {
		console.log(res, index, lists, name);
	}

	// 提交
	const submit = () => {
		if (!form.value.content) {
			return uToast('内容不能为空！');
		}
		form.value.title = form.value.content;
		// 通过filter，筛选出上传进度为100的文件(因为某些上传失败的文件，进度值不为100，这个是可选的操作)
		let files = lists.value.filter((val: any) => {
			return val.progress == 100;
		}).map((key: any) => {
			return key.response && key.response.data
		}).join(',');
		form.value.images = files;
		addCreate();
	}
	
	const onListChange = (e: any) => {
		console.log(toRaw(e));
		lists.value = toRaw(e)
	}
    // 添加请求
    const addCreate = () => {
        apiCreateBlog(form.value).then((res: any) => {
            console.log(res);
			if (res.code === 200) {
				uToast('发表成功！');
				uni.navigateBack();
			} else {
			 	uToast('发表内容失败！');
			}
        })
    }

</script>
    
<style lang="scss" scoped>
@import "./index.scss";
</style>